package com.taotao.service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.taotao.result.PictureResult;
import com.taotao.utils.FtpUtil;
import com.taotao.utils.IDUtils;

@Service
public class PictureServiceImlp implements PictureService {
	@Value("${FTP_SERVICE_IP}")
	private String FTP_SERVICE_IP;

	@Value("${FTP_SERVICE_PORT}")
	private Integer FTP_SERVICE_PORT;

	@Value("${FTP_SERVICE_USERNAME}")
	private String FTP_SERVICE_USERNAME;

	@Value("${FTP_SERVICE_PASSWORD}")
	private String FTP_SERVICE_PASSWORD;

	@Value("${FILE_UPLOAD_PATH}")
	private String FILE_UPLOAD_PATH;
	
	@Value("${FILE_UPLOAD_URL}")
	private String FILE_UPLOAD_URL;

	@Override
	public PictureResult uploadFile(MultipartFile uploadFile) {
		try {
			if(uploadFile.isEmpty()){
				return null;
			}
			
			String filePath = new DateTime().toString("/yyyy/MM/dd");
			String originalfileName = uploadFile.getOriginalFilename();
			String filename = IDUtils.genImageName() + originalfileName.substring(originalfileName.lastIndexOf("."));

			boolean file = FtpUtil.uploadFile(FTP_SERVICE_IP, FTP_SERVICE_PORT, FTP_SERVICE_USERNAME,
					FTP_SERVICE_PASSWORD, FILE_UPLOAD_PATH, filePath, filename, uploadFile.getInputStream());

			if (file) {
				return new PictureResult(0, FILE_UPLOAD_URL + filePath +"/"+ filename);
			}
			return new PictureResult(1,"上传失败");
			
		} catch (IOException e) {
			e.printStackTrace();
			return new PictureResult(1,"上传出现异常");
		}

	}

}
